package yambal.net.google.Photo
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	
	import yambal.net.google.events.PicasaAlbumEvent;
	import yambal.net.google.events.PicasaPhotoEvent;
	
	[Event(name="add_photo", type='yambal.net.google.events.PicasaAlbumEvent')]
	[Event(name="list_photo", type='yambal.net.google.events.PicasaAlbumEvent')]
	[Event(name="update_photo", type='yambal.net.google.events.PicasaPhotoEvent')]
	public class PicasaAlbum extends EventDispatcher
	{
		public var picasa:Picasa;
		public var published:Date;
		public var updated:Date;
		public var title:String;
		public var summary:String;
		public var name:String;
		public var access:String;
		public var timestamp:String;
		public var numphotos:int;
		public var numphotosremaining:int;
		public var bytesUsed:uint;
		public var nickname:String;
		public var commentingEnabled:Boolean;
		public var commentCount:uint;
		public var edit_endpoint:String;
		
		public var photos:ArrayCollection;
		
		// id
		private var _id:String;
		public function set id(id:String):void{
			this._id = id;
			if(this.user != null){
				this.listPhotos();
			}
		}
		public function get id():String{
			return this._id;
		}
		
		// user
		private var _user:String;
		public function set user(user:String):void{
			this._user = user;
			if(this.id != null){
				this.listPhotos();
			}
		}
		public function get user():String{
			return this._user;
		}
		
		// -----------------------------------------------------------------
		public override function toString():String{
			return this.title + " " + 
					"id:" + this.id + " " +
					"published:" + this.published + " " + 
					"updated:" + this.updated + " " + 
					"summary:" + this.summary + " " + 
					"name:" + this.name + " " + 
					"access:" + this.access + " " + 
					"timestamp:" + this.timestamp + " " + 
					"numphotos:" + this.numphotos + " " + 
					"bytesUsed:" + this.bytesUsed + " " + 
					"user:" + this.user + " " + 
					"nickname:" + this.nickname + " " + 
					"commentingEnabled:" + this.commentingEnabled + " " + 
					"commentCount:" + this.commentCount;
		}
		
		// -----------------------------------------------------------------
		/**
		 * Albumに登録されているPhotoを取得し、photosに格納する
		 **/
		private var isRequestingPhotoList:Boolean = false;
		public function listPhotos():void{
			if(this.id != null && this.user != null && this.isRequestingPhotoList == false){
				this.isRequestingPhotoList = true;
				this.photos = new ArrayCollection();
				
				var loader:URLLoader = new URLLoader();
				loader.addEventListener(Event.COMPLETE, this.onResultPhotos);
			
				var req:URLRequest = new URLRequest();
				req.method = "POST";
				if(this.picasa.Auth != null){
					req.url = "http://picasaweb.google.com/data/feed/api/user/default/albumid/" + this.id;
					req.requestHeaders.push(new URLRequestHeader('Authorization', 'GoogleLogin auth=' + this.picasa.Auth.auth));
				}else{
					req.url = "http://picasaweb.google.com/data/feed/api/user/"+this.user+"/albumid/" + this.id;
				}
				
				loader.load(req);
			}
		}
		
		private function onResultPhotos(e:Event):void{
			var loader:URLLoader = e.currentTarget as URLLoader;
			loader.removeEventListener(Event.COMPLETE, this.onResultPhotos);
			
			var res:XML = new XML(loader.data);
			var atom:Namespace = res.namespace();
			
			var photos:Array = new Array();
			for each (var entry:XML in res.atom::entry) {
				var p:PicasaPhoto = this.parseToPhoto(entry);
				photos.push(p);
			}
			this.photos = new ArrayCollection(photos);
			
			this.isRequestingPhotoList = false;
			this.dispatchEvent(new PicasaAlbumEvent(PicasaAlbumEvent.LIST_PHOTO, this, null, photos));
			this.picasa.onListPhoto(this,this.photos.toArray());
		}

		public function get EndPoint():String{
			return "http://picasaweb.google.com/data/feed/api/user/" + this.user + "/albumid/" + this.id;
		}
		
		// --------------------------------------------------------------------
		/**
		 * JPEGのByteArrayを投稿する
		 **/
		public function postJPG(ba:ByteArray, file_name:String):void{			
			this.postImage(ba, file_name, 'image/jpeg');
		}
		
		/**
		 * PNGのByteArrayを投稿する
		 **/
		public function postPNG(ba:ByteArray, file_name:String):void{			
			this.postImage(ba, file_name, 'image/png');
		}
		
		private function postImage(ba:ByteArray, file_name:String, mime_type:String):void{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, this.onPostImage);
			
			var req:URLRequest = new URLRequest();
			req.url = this.EndPoint;
			req.method = URLRequestMethod.POST;
			
			// Postのためのヘッダ情報
			req.requestHeaders.push(new URLRequestHeader('Authorization', 'GoogleLogin auth=' + this.picasa.Auth.auth));	
			req.requestHeaders.push(new URLRequestHeader('Content-Type', mime_type));
			req.requestHeaders.push(new URLRequestHeader('Content-Length', String(ba.length)));
			req.requestHeaders.push(new URLRequestHeader('Slug',file_name));
				
			req.data = ba;

			loader.load(req);
		}
		
		private function onPostImage(e:Event):void{
			var loader:URLLoader = e.currentTarget as URLLoader;
			loader.removeEventListener(Event.COMPLETE, this.onPostImage);
			
			
			
			var res:XML = new XML(loader.data);
			
			trace(res);
			
			var photo:PicasaPhoto = this.parseToPhoto(res);
			this.photos.addItem(photo);

			this.dispatchEvent(new PicasaAlbumEvent(PicasaAlbumEvent.ADD_PHOTO, this, photo, this.photos.toArray()));
			this.picasa.onAddPhoto(this, photo, this.photos.toArray());
		}
		
		// --------------------------------------------------------------------
		/**
		 * 配下のPHOTOがアップデートした時にソレ自身から呼び出し
		 * イベントをListenしない工夫なんだけど、如何わしいな。
		 **/
		public function onUpdatePhoto(updated:PicasaPhoto):void{
			this.dispatchEvent(new PicasaPhotoEvent(PicasaPhotoEvent.UPDATE_PHOTO, updated));
			this.picasa.onUpdatePhoto(updated);
		}
		
		// --------------------------------------------------------------------
		/**
		 * entryをPicasaPhotoにパースする
		 **/
		public function parseToPhoto(entry:XML):PicasaPhoto{
			var atom:Namespace = entry.namespace();
			var gphoto:Namespace = entry.namespace('gphoto');
			var media:Namespace = entry.namespace('media');
			
			var photo:PicasaPhoto = new PicasaPhoto();
			photo.album = this;
			photo.id = entry.gphoto::id;
			photo.title = entry.atom::title;
			photo.summary = entry.atom::summary;
			photo.version = entry.gphoto::version;
			photo.access = entry.gphoto::access;
			photo.width = entry.gphoto::width;
			photo.height = entry.gphoto::height;
			photo.size = entry.gphoto::size;
			photo.timestamp = entry.gphoto::timestamp;
			
			var mgroup:XMLList = entry.media::group;
			photo.src = mgroup.media::content.@url;
			for each (var thums:XML in mgroup.media::thumbnail) {
				if(thums.@height == "72" || thums.@width == "72"){
					photo.s_src = thums.@url;
				}else if(thums.@height == "144" || thums.@width == "144"){
					photo.m_src = thums.@url;
				}else{
					photo.l_src = thums.@url;
				}
			}
			
			var links:XMLList = entry.atom::link;
			for each (var link:XML in entry.atom::link) {
				if(link.@rel == "edit"){
					photo.edit_mata_endpoint = link.@href;
				}
			}
			
			return photo;
		}
	}
	
	
}